<template>
  <el-collapse>
    <el-collapse-item title="变量设置">
      <text-add-button @click="handleVariableAdd" />
      <el-table :data="variables" border>
        <el-table-column align="center" prop="variable" label="流程变量">
          <template #default="scope">
            <el-select v-model="scope.row.variable" clearable>
              <el-option v-for="opt in globalVariables" :key="opt.id" :label="opt.name" :value="opt.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="type" label="设置类型">
          <template #default="scope">
            <el-select v-model="scope.row.type">
              <el-option v-for="opt in typeOptions" :label="opt.label" :value="opt.value" :key="opt.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="value" label="设置值">
          <template #default="scope">
            <el-input v-model="scope.row.value" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <text-delete-button @click="handleVariableDelete(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
    </el-collapse-item>
  </el-collapse>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { mapState } from 'pinia';
import modelerStore from '@wf/components/bpmnjs/store/modeler';
import { getVariableSetTaskValue, setVariableSetTaskValue } from '@wf/components/bpmnjs/bo-utils/serviceTaskUtil';
import { getGlobalVariablesValue } from '@wf/components/bpmnjs/bo-utils/globalVariablesUtil';

export default defineComponent({
  name: 'ElementVariableSetTask',
  data() {
    return {
      variables: [],
      globalVariables: [],
      typeOptions: [
        { label: '设置', value: 'set' },
        { label: '清空', value: 'clear' },
        { label: '删除', value: 'delete' },
        { label: '加上', value: 'plus' },
        { label: '减去', value: 'minus' },
        { label: '乘以', value: 'multiply' },
        { label: '除以', value: 'divide' }
      ]
    };
  },
  computed: {
    ...mapState(modelerStore, ['getActive', 'getActiveId'])
  },
  watch: {
    variables: {
      handler(newVal) {
        setVariableSetTaskValue(this.getActive, newVal);
      },
      deep: true
    }
  },
  mounted() {
    this.getVariables();
    this.getGlobalVariables();
  },
  methods: {
    getGlobalVariables() {
      this.globalVariables = getGlobalVariablesValue(this.getActive.businessObject.$parent);
    },
    getVariables() {
      this.variables = getVariableSetTaskValue(this.getActive);
    },
    handleVariableAdd() {
      this.variables.push({
        variable: '',
        type: '',
        value: ''
      });
    },
    handleVariableDelete(index) {
      this.variables.splice(index, 1);
    }
  }
});
</script>
